﻿
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Utils.Common;

namespace ZK.Pack
{
   public class SerialPortManualScanner:SerialPortScanner
    {
        private object sync = new object();
        private char stop = '\r';
        private char n = '\n';

        private StringBuilder stringBuilder = new StringBuilder(); 

        public SerialPortManualScanner(string portName, int baudRate) : base(portName, baudRate)
        {

        }

      

        //打开并启动线程
        public override void Open()
        {
            base.Open();
            stringBuilder.Clear();
        }

        public override void Close()
        {
            base.Close();
           
        }

 
        protected override void OnDataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            if (e.EventType == SerialData.Eof)
            {
                return;
            }
            SerialPort serialPort = (SerialPort)sender;
            while (serialPort.BytesToRead > 0)
            {

                char chr = (char)serialPort.ReadChar();
                stringBuilder.Append(chr);
                if (chr != this.stop)
                {
                    continue;
                }
                else
                {
                    string str = stringBuilder.ToString().TrimEnd(new char[] { this.stop,this.n });
                    base.OnDataReceived(str, null);
                    stringBuilder.Clear();
                }

            }
 
        }

    }
}
